package com.fch.sdlibrary.ui.notifications;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.fch.sdlibrary.LoginActivity;
import com.fch.sdlibrary.R;
import com.fch.sdlibrary.entity.BaseResponse;
import com.fch.sdlibrary.entity.Book;
import com.fch.sdlibrary.entity.User;
import com.fch.sdlibrary.global.MyGlobal;
import com.fch.sdlibrary.util.TokenInterceptor;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

import static android.content.Context.MODE_PRIVATE;

public class NotificationsFragment extends Fragment {

    private NotificationsViewModel notificationsViewModel;
    private BaseResponse baseResponse;
    private TextView username, bookUser;
    private Button logout, remand;
    private SharedPreferences userInfo;
    private User user;
    private Gson gson = new Gson();
    private Book book;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        notificationsViewModel =
                ViewModelProviders.of(this).get(NotificationsViewModel.class);
        final View root = inflater.inflate(R.layout.fragment_notifications, container, false);

        init(root);
        getBook(root);

        userInfo = root.getContext().getSharedPreferences("data", MODE_PRIVATE);
        String json = userInfo.getString("user", "");


        if (!"".equals(json)) {
            user = gson.fromJson(json, User.class);
            username.setText("欢迎：" + user.getUserName());
        }


        /**
         * 还书
         */
        remand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OkHttpClient client = new OkHttpClient.Builder()
                        .addInterceptor(new TokenInterceptor(getActivity()))//拦截器
                        .build();//创建Http客户端
                Request request = new Request.Builder()
                        .url(MyGlobal.PATH + "Remand")//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                        .post(new RequestBody() {
                            @Override
                            public MediaType contentType() {
                                return MyGlobal.JSON;
                            }

                            @Override
                            public void writeTo(BufferedSink sink) throws IOException {

                            }
                        })
                        .build();//创建Http请求
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //请求失败的处理
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //请求成功返回结果
                        //如果希望返回的是字符串
                        final String responseData = response.body().string();
                        baseResponse = new BaseResponse();
                        baseResponse = gson.fromJson(responseData, baseResponse.getClass());

                        if (baseResponse.getCode() == 401) {
                            Intent intent = new Intent(getActivity(), LoginActivity.class);
                            startActivity(intent);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), "请登录", Toast.LENGTH_SHORT).show();
                                }
                            });
                            return;
                        }
                        if (baseResponse.getCode() == 200) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if ("还书成功".equals(baseResponse.getMsg())){
                                        bookUser.setText("当前借阅:无");
                                        Toast.makeText(getActivity(), baseResponse.getMsg(), Toast.LENGTH_SHORT).show();
                                        remand.setVisibility(View.GONE);
                                    }
                                    else
                                        Toast.makeText(getActivity(), baseResponse.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
            }
        });

        /**
         * 退出登录
         */
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences.Editor editor = userInfo.edit();//获取Editor
                editor.clear();
                editor.apply();
                OkHttpClient client = new OkHttpClient.Builder()
                        .build();//创建Http客户端

                Request request = new Request.Builder()
                        .url(MyGlobal.PATH + "logout")//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                        .post(new RequestBody() {
                            @Override
                            public MediaType contentType() {
                                return null;
                            }

                            @Override
                            public void writeTo(BufferedSink sink) throws IOException {
                            }
                        })
                        .build();//创建Http请求
                client.newCall(request);
                Intent intent = new Intent(root.getContext(), LoginActivity.class);
                startActivity(intent);
                username.setText("请登录");
                bookUser.setVisibility(View.GONE);
            }
        });
        return root;
    }

    private void getBook(final View root) {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new TokenInterceptor(root.getContext()))//拦截器
                .connectTimeout(3, TimeUnit.SECONDS)
                .build();//创建Http客户端
        Request request = new Request.Builder()
                .url(MyGlobal.PATH + "GetUserBook")//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                .post(new RequestBody() {
                    @Override
                    public MediaType contentType() {
                        return MyGlobal.JSON;
                    }

                    @Override
                    public void writeTo(BufferedSink sink) throws IOException {

                    }
                })
                .build();//创建Http请求
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败的处理
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        Toast.makeText(getContext(), "链接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功返回结果
                //如果希望返回的是字符串
                final String responseData = response.body().string();
                baseResponse = new BaseResponse<Book>();
                Type type = new TypeToken<BaseResponse<Book>>() {
                }.getType();
                baseResponse = gson.fromJson(responseData, type);

                if (baseResponse.getCode() == 401) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "请登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                if (baseResponse.getCode() == 200) {
                    book = (Book) baseResponse.getData();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (book != null) {
                                bookUser.setText("当前借阅:" + book.getBookName());
                                remand.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                }
            }
        });
    }

    private void init(View root) {
        bookUser = root.findViewById(R.id.book_user);
        username = root.findViewById(R.id.username);
        logout = root.findViewById(R.id.logout);
        remand = root.findViewById(R.id.remand);
    }


}